using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.Events;

namespace Life.ESound
{
    public class BgmAudioPlayer : MonoBehaviour
    {
        
        public AudioSource audioSource;
        [ShowInInspector][ReadOnly] private bool isPlaying;
        [ShowInInspector][ReadOnly] private bool isPaused;
        [Header("播放结束事件")]
        private UnityEvent onFinished = new UnityEvent();
        
        public UnityEvent OnFinished => onFinished;
        public bool IsPlaying => isPlaying;
        public bool IsPaused => isPaused;
        public bool loop { get; set; }
        
        private void Update()
        {
            if (audioSource == null) return;
            if (isPlaying && !audioSource.isPlaying && !isPaused)
            {
                isPlaying = false;
                onFinished?.Invoke();
                if (loop)
                {
                    audioSource.Play();
                    isPaused = false;
                    isPlaying = true;
                }
            }
        }

        /// <summary>
        /// 播放音频
        /// </summary>
        public void Play(AudioClip clip)
        {
            if (clip == null)
            {
                Debug.LogWarning("AudioPlayerWithEvent: 未设置 AudioClip");
                return;
            }

            audioSource.clip = clip;
            Play();
        }

        void Play()
        {
            audioSource.Play();
            isPaused = false;
            isPlaying = true;
        }

        public float volume
        {
            get => audioSource.volume;
            set => audioSource.volume = value;
        }
        
        /// <summary>
        /// 停止播放
        /// </summary>
        public void Stop()
        {
            audioSource.Stop();
            isPlaying = false;
            isPaused = false;
        }

        public void Pause()
        {
            if (isPlaying)
            {
                audioSource.Pause();
                isPaused = true;
            }
        }

        public void Resume()
        {
            if (isPaused)
            {
                audioSource.UnPause();
                isPaused = false;
                return;
            }

            if (!isPlaying && audioSource.clip != null)
            {
                Play();
            }
        }
    }
}
